package com.baoji.auth.service.impl;

import com.baoji.auth.entity.Role;
import com.baoji.auth.entity.User;
import com.baoji.auth.mapper.UserMapper;
import com.baoji.auth.model.AccountErrorCode;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * @Auther: ghm
 * @Date: 2021/09/24/14:53
 * @Description: 用户登录认证的业务代码
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        if (username == null || "".equals(username)) {
            throw new RuntimeException(AccountErrorCode.USERNAME_ISNONULL.getMessage());
        }

        // 调用方法查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new RuntimeException(AccountErrorCode.USER_NOT_REGISTER.getMessage());
        }


        // 获取用户的权限信息
        ArrayList<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (Role role : userMapper.findRoleByUsername(username)) {
                authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
        }
        // 用数据库查询的用户信息进行校验
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorities);
    }
}
